package com.ruoyi.search.controller;

import cn.easyes.core.biz.EsPageInfo;
import cn.easyes.core.conditions.LambdaEsQueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;


import com.ruoyi.search.domain.SearchArticleVo;
import com.ruoyi.search.domain.UserSearchDto;
import com.ruoyi.search.esmapper.SearchArticleMapper;
import com.ruoyi.search.mapper.ApArticleMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@ConditionalOnProperty(value = "easy-es.enable", havingValue = "true")
@RestController
@RequiredArgsConstructor
@RequestMapping("/search")
public class ArticleSearchController {

    private final ApArticleMapper apArticleMapper;

    private final SearchArticleMapper searchArticleMapper;


    @PostMapping
    public R<List<SearchArticleVo>> search(@RequestBody UserSearchDto dto) throws IOException {
        //校验参数
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            throw new ServiceException("参数错误");
        }


        LambdaEsQueryWrapper<SearchArticleVo> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.match(SearchArticleVo::getTitle, dto.getSearchWords());
            //.lt(SearchArticleVo::getPublishTime,dto.getMinBehotTime())
            //.and(w->w.like(SearchArticleVo::getTitle, dto.getSearchWords()).or().like(SearchArticleVo::getContent,dto.getSearchWords()));

        //分页查询
        //wrapper.size(dto.getPageSize());
        //wrapper.orderByDesc(SearchArticleVo::getId);
        EsPageInfo<SearchArticleVo> searchArticleVoPageInfo = searchArticleMapper.pageQuery(wrapper, 0, dto.getPageSize());
        return R.ok(searchArticleVoPageInfo.getList());
    }

    @GetMapping("/init")
    public R<Void> init() throws IOException {
        //1.查询所有符合条件的文章数据
        List<SearchArticleVo> searchArticleVos = apArticleMapper.loadArticleList();

        for (SearchArticleVo searchArticleVo : searchArticleVos) {
            searchArticleMapper.insert(searchArticleVo);
        }
        return R.ok("初始化成功");
    }
}
